import React, { useState,useEffect } from 'react';
import { Button, Table, Tag, message } from 'antd';
import type {PaginationProps } from 'antd'
import type { ColumnsType } from 'antd/es/table';


// 路由
import { Outlet,useLocation,useNavigate } from "react-router-dom";


import {useSelector,useDispatch } from 'react-redux'
import type { StoreState, StoreDispatch } from '../../store'
// 异步任务
import { getcostlist,deldata } from '../../store/modules/cost/cost'
// 同步任务
import {changeisdel} from '../../store/modules/cost/cost'


import Screen from '../../components/CostOutConsume/CostOutConsumeScreen';

import monent from 'moment'

monent.locale('zh-cn');


import {
  FileTextOutlined,
  EditOutlined,
  RestOutlined
} from '@ant-design/icons';


// 表格数据类型
interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
}



export default function CostOutConsume() {


  // 全选中的表格数据
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  //
  const [loading, setLoading] = useState(false);

  // 派发任务
  const dispatch: StoreDispatch = useDispatch();

  // cost仓库状态
  const {cost:{costlist,costlistnum,isdel}} = useSelector((state: StoreState)=>state)

  // 轻提示
  const [messageApi, contextHolder] = message.useMessage();

  // 路由信息
  const { pathname } = useLocation();
  // 路由切换
  const navigate = useNavigate();



  // 表单配置项
  // 表头设置,配置项
  const columns: ColumnsType<DataType> = [
    {
      title: '操作时间',
      dataIndex: 'time',
      render: (item) => {
        const date = monent(item).format("YYYY-MM-DD h:mm:ss");
        return (
          <div>{date}</div>
        )
      }
    },
    {
      title: '订单号',
      dataIndex: 'orderId',

    },
    {
      title: '患者姓名',
      dataIndex: 'username',

    },
    {
      title: '就诊卡号',
      dataIndex: 'visitID',

    },
    {
      title: '来源',
      dataIndex: 'from',

    },
    {
      title: '业务类型',
      dataIndex: 'Business',

    },
    {
      title: '费用类型',
      dataIndex: 'Costtype',

    },
    {
      title: '支付方式',
      dataIndex: 'uocost',

    },
    {
      title: '支付金额',
      dataIndex: 'addresscost',

    },
    {
      title: '缴费状态',
      dataIndex: 'Paymentstatus',

      render: (item) => {
        let color
        if (item == '未缴费') {
          color = 'red'
        } else if (item == '已缴费') {
          color = 'green'
        } else if (item == '缴费异常') {
          color = 'yellow'
        }
        return (
          <Tag color={ color }>{ item}</Tag>
        )
      }
    },
    {
      title: '操作',
      dataIndex: 'cz',
      render: (data,item,index) => {
        // console.log('data',data,item,index);

        return (
          <span >
            <FileTextOutlined onClick={()=>todetails(item)} style={{ fontSize: "20px", color: "#006eff" }}/>
            <EditOutlined onClick={()=>tochange(item)} style={{ fontSize: "20px", color: "#006eff" }}/>
            <RestOutlined onClick={()=>todel(item)} style={{ fontSize: "20px", color: "#006eff" }}/>
          </span>
        )
      }
    },
  ];


  // 切换详情
  const todetails = (item: any) => {
    navigate({pathname:`/Costmsg/CostOutConsume/CostOutConsume-detail/${item.id}`})
    console.log("todetails",item);
  }
  // 到修改状态页面
  const tochange = (item: any) => {
    navigate({pathname:`/Costmsg/CostOutConsume/CostOutConsume-change/${item.id}`})
    console.log("tochange",item);
  }

  const todel = (item: any) => {
    // 派发删除任务
    dispatch(deldata({ id: [item.id] }))

  }

  const toadd = () => {
    navigate({pathname:`/Costmsg/CostOutConsume/CostOutConsume-add`})

  }

  // 监听是否删除成功
  useEffect(() => {
    console.log("切换");
    if (isdel) {
      console.log("isdel",isdel);
      messageApi.open({
        type: 'success',
        content: '删除数据成功!',
      });
      dispatch(changeisdel())
    }
  }, [isdel])


  // mount
  useEffect(() => {
    dispatch(getcostlist());

  },[dispatch])


  // console.log('costlist',costlist);





  // 按钮延时操作（做批量删除）
  const start = () => {

    console.log('selectedRowKeys',selectedRowKeys);
    dispatch(deldata({ id: selectedRowKeys }))
    
    setLoading(true);
    setTimeout(() => {
      setSelectedRowKeys([]);
      setLoading(false);
    }, 1000);
  };

  // 全选事件
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  // 表单能实现的操作
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const hasSelected = selectedRowKeys.length > 0;

  // 选中表格信息
  const tabonChange = (...data:any) => {
    console.log(data);
    
  }


  // 分页器切换
  const onChange: PaginationProps['onChange'] = (pageNumber) => {

    dispatch(getcostlist({offset:(pageNumber-1)*10}));

    console.log('Page: ', pageNumber);
  }

  return (
    // 门诊消费记录
    <>
      {
        pathname === '/Costmsg/CostOutConsume' ?
          <div>
            {contextHolder}
            <div style={{ marginBottom: 16, display: 'flex' }}>
              <Button
                style={{ marginRight: "24px" }}
                type="primary"
                onClick={start}
                disabled={!hasSelected} loading={loading}>
                删除
              </Button>
              <Button style={{ marginRight:"24px" }} type="primary" onClick={toadd}> 新增 </Button>

              <Screen></Screen>
            </div>
            <Table
              // 表单能实现的操作也就是事件
              rowSelection={rowSelection}
              columns={columns}
              dataSource={costlist}
              onChange={tabonChange}
              // 分页器能实现的事件
              pagination={{
                showQuickJumper: true,
                // 默认打开页数
                defaultCurrent: 1,
                // 总数量
                total: costlistnum,
                onChange:onChange
              } } />
          </div> :
          <Outlet />
      }




    </>
  )
}
